package com.blb.eduuserservice.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blb.common.util.JwtUtils;
import com.blb.common.util.ResponseResult;
import com.blb.common.util.RsaUtils;
import com.blb.eduuserservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功处理器
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserService userService;

    /**
     * 登录成功后的回调方法
     * 参数1 请求 参数2 响应 参数3 验证信息
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //获得登录的用户信息
        User user = (User)authentication.getPrincipal();
        //查询用户数据库信息
        com.blb.common.entity.User user1 = userService.getOne(new QueryWrapper<com.blb.common.entity.User>().lambda().eq(com.blb.common.entity.User::getUsername,user.getUsername()));
        //将用户信息转换为JWT
        String token = JwtUtils.generateUserToken(user1, RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES);
        System.out.println("生成JWT:" + token);
        //将JWT包装到ResponseResult中转换为json格式=发送json
        ResponseResult.write(httpServletResponse, ResponseResult.ok(user1,token,""));
    }
}
